package com.smartcampusbackend.service.impl;

import com.smartcampusbackend.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenServiceImpl implements TokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String TOKEN_PREFIX = "token:";
    private static final long TOKEN_EXPIRE_SECONDS = 2 * 60 * 60; // 2小时

    @Override
    public void saveToken(String token, String username) {
        log.info("Saving token: {} for user: {}", token, username);
        redisTemplate.opsForValue().set(TOKEN_PREFIX + token, username, TOKEN_EXPIRE_SECONDS, TimeUnit.SECONDS);
        log.info("Token saved in Redis: {}", TOKEN_PREFIX + token);
    }

    @Override
    public void removeToken(String token) {
        log.info("Removing token: {}", token);
        redisTemplate.delete(TOKEN_PREFIX + token);
    }

    @Override
    public String getUsernameByToken(String token) {
        String username = redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        log.info("Getting username for token: {} -> {}", token, username);
        return username;
    }
}